package com.docjohnson.pamphlet.activities;

import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;

import com.docjohnson.pamphlet.R;
import com.docjohnson.pamphlet.dialogs.Dialogs;
import com.docjohnson.pamphlet.utils.Constants;
import com.docjohnson.pamphlet.utils.JsonConstants;
import com.docjohnson.pamphlet.utils.NetUtils;
import com.docjohnson.pamphlet.utils.PamphletPreferences;
import com.docjohnson.pamphlet.utils.Utils;

public class SplashActivity extends DefaultActivity implements JsonConstants {
	static {
		new File(Constants.CACHE_DIR).mkdirs();
		new File(Constants.CACHE_PAMPHLETS_DIR).mkdirs();
		new File(Constants.CACHE_SCREEN_SAVER_DIR).mkdirs();
	}
	
	private static final String TAG = SplashActivity.class.getSimpleName();

	PamphletPreferences preferences;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash);
		init();
	}

	private void init() {
		preferences = new PamphletPreferences(this);
		getApplicationConfiguration();
	}

	private void getApplicationConfiguration() {

		Dialogs.showProgressDialog(this);

		ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
		service.schedule(new Runnable() {

			@Override
			public void run() {
				String jsonResponse = null;
				if (Utils.isConnectedOrConnecting(SplashActivity.this)) {
					jsonResponse = NetUtils.getResponse(Constants.SERVER_URL);

					if (jsonResponse != null) {
						Dialogs.setProgressDialogMessage(SplashActivity.this, "updateing configuration ... ");
						updateAppConfiguration(jsonResponse);
					}
				}

				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Dialogs.closeProgressDialog(SplashActivity.this);
						startDashboard();
					}
				});
			}
		}, SPLASH_DELAY, TimeUnit.MILLISECONDS);
	}

	private void downloadPamphletMediaList(String pamphletId, JSONObject pamphletContent) throws JSONException {
		String dir = Constants.CACHE_PAMPHLETS_DIR + pamphletId + "/";
		Iterator<String> keys = pamphletContent.keys();
		Dialogs.setProgressDialogMessage(SplashActivity.this, "downloading pamphlet image list");
		while (keys.hasNext()) {
			String key = keys.next();

			JSONObject content = null;
			try {
				content = pamphletContent.getJSONObject(key);
			} catch (Exception e) {
				continue;
			}

			Iterator<String> contentKeys = content.keys();

			while (contentKeys.hasNext()) {
				String contentKey = contentKeys.next();
				JSONObject contentContent = null;

				try {
					contentContent = content.getJSONObject(contentKey);
				} catch (Exception e) {
					continue;
				}

				if (!contentContent.isNull(IMAGEURL)) {
					String imageUrl = contentContent.getString(IMAGEURL);

					String imagePath = dir + "/" + contentContent.getString(IMAGE);

					if (!fileExists(imagePath))
						NetUtils.downloadFile(imageUrl, imagePath);
				}

				if (!contentContent.isNull(FAVORITES)) {
					JSONArray favourites = contentContent.getJSONArray(FAVORITES);

					for (int i = 0, len = favourites.length(); i < len; ++i) {
						JSONObject favourite = favourites.getJSONObject(i);

						if (!favourite.isNull(VIDEOLINK)) {
							String videoLink = favourite.optString(VIDEOLINK);
							
							String localPath = Utils.mapServerFileToLocal(pamphletId, videoLink);

							if (!fileExists(localPath))
								NetUtils.downloadFile(videoLink, localPath);
						}
						
						if (!favourite.isNull(PRODUCT)) {
							JSONObject product = favourite.optJSONObject(PRODUCT);

							if (!product.isNull(IMAGE)) {
								String imageUrl = product.optString(IMAGE);

								String localPath = Utils.mapServerFileToLocal(pamphletId, imageUrl);

								if (!fileExists(localPath))
									NetUtils.downloadFile(imageUrl, localPath);
							}

							if (!product.isNull(THUMBNAIL)) {
								JSONArray thumbnails = product.optJSONArray(THUMBNAIL);

								for (int j = 0, count = thumbnails.length(); j < count; ++j) {
									String url = thumbnails.getString(j);

									String localPath = Utils.mapServerFileToLocal(pamphletId, url);

									if (!fileExists(localPath))
										NetUtils.downloadFile(url, localPath);
								}
							}
						}
					}
				}
			}
		}
	}

	private void downloadMedia(JSONObject json) throws JSONException {
		File pamphletSaveDir = new File(Constants.CACHE_PAMPHLETS_DIR);
		pamphletSaveDir.mkdirs();

		JSONArray pamphlets = json.getJSONArray(PAMPHLETS);

		ArrayList<String> pamphletsList = getPamphletListFromSdcard();

		Dialogs.setProgressDialogMessage(SplashActivity.this, "updateing pamphlets ... ");

		for (int i = 0, count = pamphlets.length(); i < count; ++i) {
			JSONObject pamphlet = pamphlets.getJSONObject(i);

			int id = pamphlet.getInt(ID);

			Dialogs.setProgressDialogMessage(SplashActivity.this, "pamphlet id : " + id + " " + i + " / " + count);

			int pamphletIndex = pamphletsList.indexOf(String.valueOf(id));

			if (pamphletIndex != -1) {
				pamphletsList.remove(pamphletIndex);
			}

			updatePamphlet(pamphlet);
		}

		deletePamphlets(pamphletsList);

		String dashboarUrl = json.getString(DASHBOARD);

		String dashboardSavePath = Constants.CACHE_DIR + dashboarUrl.substring(dashboarUrl.lastIndexOf("/") + 1);

		preferences.saveDashboardImage(dashboardSavePath);

		if (!fileExists(dashboardSavePath))
			NetUtils.downloadFile(dashboarUrl, dashboardSavePath);

		int rotationSpeed = json.getInt(ROTATION_SPEED);
		JSONObject screen = json.getJSONObject(SCREEN);
		long screenSaverDelay = screen.getLong(DELAY);
		JSONArray screenSavers = screen.getJSONArray(IMAGES);

		Set<String> imageList = new HashSet<String>();

		for (int i = 0, count = screenSavers.length(); i < count; ++i) {
			String imageUrl = screenSavers.get(i).toString();
			String savePath = Constants.CACHE_SCREEN_SAVER_DIR + imageUrl.substring(imageUrl.lastIndexOf("/") + 1);

			imageList.add(savePath);

			if (!fileExists(savePath))
				NetUtils.downloadFile(imageUrl, savePath);
		}

		preferences.saveScreenSaverImages(imageList);
		preferences.saveScreenSaverDelay(screenSaverDelay * 1000);
		preferences.saveRotationSpeed(rotationSpeed);
	}

	private void updateAppConfiguration(String jsonStr) {

		if(jsonStr.startsWith("<xmp>")){
			jsonStr = jsonStr.substring(5);
		}
		try {
			JSONObject json = new JSONObject(jsonStr);
			int serverAppVersion = json.getInt(VERSION);

//			int localAppVersion = preferences.getAppVersion();

			JSONArray pamphlets = json.getJSONArray(PAMPHLETS);
			preferences.savePamphlets(pamphlets.toString());

			downloadMedia(json);

			preferences.setAppVersion(serverAppVersion);
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void updatePamphlet(JSONObject pamphlet) throws JSONException {
		int pamphletId = pamphlet.getInt(ID);

		String dir = Constants.CACHE_PAMPHLETS_DIR + pamphletId + "/";

		new File(dir).mkdirs();

		String imageUrl = pamphlet.getString(PAMPHLETIMAGE);
		String bgUrl = pamphlet.getString(BACKGROUND);
		String transitionImageUrl = pamphlet.getString(TRANSITION_IMAGE);

		String imageSavePath = dir + "image_" + pamphletId + ".jpg";
		String bgSavePath = dir + "background_" + pamphletId + ".jpg";

		String transitionImageSavePath = dir + "transition_" + pamphletId + ".jpg";

		if (!fileExists(imageSavePath)) {
			Dialogs.setProgressDialogMessage(SplashActivity.this, "downloading pamphlet image, [" + imageUrl + "]");
			NetUtils.downloadFile(imageUrl, imageSavePath);
		} else {
			Dialogs.setProgressDialogMessage(SplashActivity.this, "no need to download pamphlet image, [" + imageUrl + "]");
		}

		if (!fileExists(bgSavePath)) {
			Dialogs.setProgressDialogMessage(SplashActivity.this, "downloading pamphlet bg, [" + bgUrl + "]");
			NetUtils.downloadFile(bgUrl, bgSavePath);
		} else {
			Dialogs.setProgressDialogMessage(SplashActivity.this, "no need to download pamphlet bg, [" + bgUrl + "]");
		}

		if (!fileExists(transitionImageSavePath)) {
			Dialogs.setProgressDialogMessage(SplashActivity.this, "downloading transient image, [" + transitionImageUrl + "]");
			NetUtils.downloadFile(transitionImageUrl, transitionImageSavePath);
		} else {
			Dialogs.setProgressDialogMessage(SplashActivity.this, "no need to download transient image, [" + transitionImageUrl + "]");
		}

		try {
			downloadPamphletMediaList(String.valueOf(pamphletId), pamphlet.getJSONObject(CONTENT));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void deletePamphlets(ArrayList<String> pamphlets) {
		for (String id : pamphlets) {
			Log.d(TAG, "removing pamphlet " + id);
			try {
				deletePamphlet(id);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	private void deletePamphlet(String id) throws JSONException {
		File pamphletDir = new File(Constants.CACHE_PAMPHLETS_DIR + id);

		File[] fileList = pamphletDir.listFiles();

		if (fileList != null) {
			for (File file : fileList) {
				file.delete();
			}
		}

		pamphletDir.delete();
	}

	private ArrayList<String> getPamphletListFromSdcard() {
		ArrayList<String> pamphlets = new ArrayList<String>();

		File pamphletDir = new File(Constants.CACHE_PAMPHLETS_DIR);

		File[] fileList = pamphletDir.listFiles();

		if (fileList != null) {
			for (File file : fileList) {
				if (file.isDirectory()) {
					pamphlets.add(file.getName());
				}
			}
		}

		return pamphlets;
	}

	private boolean fileExists(String path) {
		return new File(path).exists();
	}
}
